package utils

import (
	"blogcenter/internal/types"
	"context"
	"fmt"
	"strconv"
	"time"

	"github.com/zhenghaoz/gorse/client"
)

// GorseClient 封装了 gorse 客户端，提供更友好的接口
type GorseClient struct {
	*client.GorseClient
	timeout time.Duration // 请求超时时间
}

// NewGorseClient 创建新的 Gorse 客户端实例
func NewGorseClient(host, apiKey string) *GorseClient {
	// 创建基础客户端
	gorseClient := client.NewGorseClient(host, apiKey)

	// 初始化自定义客户端
	c := &GorseClient{
		GorseClient: gorseClient,
		timeout:     5 * time.Second, // 默认超时时间
	}
	return c
}

// Option 客户端配置选项类型
type Option func(*GorseClient)

// WithTimeout 设置请求超时时间
func WithTimeout(timeout time.Duration) Option {
	return func(c *GorseClient) {
		c.timeout = timeout
	}
}

func (c *GorseClient) CreatBlogGorse(ctx context.Context, blog types.BlogRequest, tag []string, blogid int) error {
	if blog.Category == "" {
		blog.Category = "blog"
	}
	item := client.Item{
		ItemId:     strconv.Itoa(blogid),
		Labels:     ExtractKeyWord(blog.Content, 5, "textrank"),
		IsHidden:   false,
		Timestamp:  time.Now().Format(time.RFC3339),
		Categories: []string{blog.Category},
		Comment:    blog.Title, // 使用博客标题作为注释
	}

	// 如果有传入的标签，合并到 Labels 中
	if len(tag) > 0 {
		item.Labels = append(item.Labels, tag...)
	}

	row, err := c.GorseClient.InsertItem(ctx, item)
	if err != nil {
		return fmt.Errorf("failed to insert item into Gorse: %w", err)
	}

	fmt.Printf("Inserted item into Gorse, affected rows: %d\n", row)
	return nil
}

func (c *GorseClient) FeedBackGorse(ctx context.Context, userId int, itemid int, feedbacktype string, t time.Time) error {
	feedback := client.Feedback{
		FeedbackType: feedbacktype,
		UserId:       strconv.Itoa(userId),
		ItemId:       strconv.Itoa(itemid),
		Timestamp:    t.Format(time.RFC3339),
	}

	row, err := c.GorseClient.InsertFeedback(ctx, []client.Feedback{feedback})
	if err != nil {
		return fmt.Errorf("failed to insert feedback into Gorse: %w", err)
	}

	fmt.Printf("Inserted feedback into Gorse, affected rows: %d\n", row)
	return nil
}

func (c *GorseClient) LikeBlogGorse(ctx context.Context, userId int, blogid int) error {
	return c.FeedBackGorse(ctx, userId, blogid, "like", time.Now())
}

func (c *GorseClient) CommentBlogGorse(ctx context.Context, userId int, blogid int) error {
	return c.FeedBackGorse(ctx, userId, blogid, "comment", time.Now())
}

func (c *GorseClient) ReadBlogGorse(ctx context.Context, userId int, blogid int) error {
	return c.FeedBackGorse(ctx, userId, blogid, "read", time.Now())
}

func (c *GorseClient) RecommendBlogGorse(ctx context.Context, userId int, category string, n int, offset int) ([]string, error) {
	recommendations, err := c.GorseClient.GetRecommendOffSet(ctx, strconv.Itoa(userId), category, n, offset)
	if err != nil {
		return nil, fmt.Errorf("failed to get recommendations from Gorse: %w", err)
	}

	return recommendations, nil
}
